package com.tulei.douban;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.tulei.common.utils.file.ExcelHandler;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;
import static java.lang.Thread.sleep;

/**
 * @Author TuLei
 * @Date 2024-07-02 17:29
 **/

public class DouBanMovie {

    public static void main(String[] args) throws InterruptedException {

        List<Movie> list = new ArrayList<>();
        for (int i = 0; i <250; i+=25) {
            list.addAll(extracted(i));
            sleep(1000);
        }

        ObjectMapper objectMapper = new ObjectMapper();

        String currentDir = System.getProperty("user.dir");
        String fileName = "movie.txt";

        // 构建文件路径
        Path path = Paths.get(currentDir, fileName);
        try {
            // 如果文件不存在，则创建文件
            if (!Files.exists(path)) {
                Files.createFile(path);
            }

            for (Movie obj : list) {
                String jsonString = objectMapper.writeValueAsString(obj);
                Files.write(path, jsonString.getBytes(), StandardOpenOption.APPEND);
                Files.write(path, "\n".getBytes(), StandardOpenOption.APPEND);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        new ExcelHandler().writeExcel("movie.xlsx", list);

    }

    private static List<Movie> extracted(int i) {
        List<Movie> list = new ArrayList<>();
        Connection connect = Jsoup.connect("https://movie.douban.com/top250?start=" + i + "&filter=" );
        try {
            Document document = connect.get();
            Elements elements = document.getElementsByClass("grid_view");
            Elements liElements = elements.get(0).getElementsByTag("li");

            for (Element element : liElements) {
                Movie movie = new Movie();
                Element movieElement = element.selectFirst(".item");

                Elements titleElements = movieElement.select("div.info div.hd a span");
                movie.setTitle(titleElements.first().text());
                movie.setEnglishTitle(titleElements.eq(1).text().replace("/", "").trim());
                movie.setAlternativeTitles(titleElements.eq(2).text());

                Elements imgElement = movieElement.select("div.pic a img");
                String attr = imgElement.attr("src");
                movie.setImgUrl(attr);


                Elements actorElement = movieElement.select("p").eq(0);
                String[] parts = actorElement.text().split("/");
                String text="";
                int size = parts.length;
                for (int j = 0; j < size - 2; j++) {
                    text = text + parts[j];
                }
                movie.setActors(text.replaceAll("[0-9]", ""));
                movie.setYear(text.replaceAll("[^0-9]", ""));
                movie.setCountry(parts[size - 2]);
                movie.setKind(parts[size -1]);




                Element ratingElement = movieElement.selectFirst(".rating_num");
                movie.setRating(ratingElement.text());

                Element reviewCountElement = movieElement.selectFirst(".star").select("span").last();
                movie.setReviewCount(reviewCountElement.text());

                Element quoteElement = movieElement.selectFirst(".quote .inq");
                if (quoteElement != null) {
                    movie.setQuote(quoteElement.text());
                }
                list.add(movie);

            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return list;
    }
}
